package uit.minito.suggestion;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;

public class SuggestionEditText extends AutoCompleteTextView {
	//this is the suggestion provider;
	SuggestionAdapter adapter;
	private SuggestionModel currentSuggestion;
	private boolean userHasChosenASuggestion=false;  
	//ArrayList<FetchSuggestionTask> taskList=new ArrayList<FetchSuggestionTask>();
	
	/*
	@Override
	protected void onTextChanged(CharSequence text, int start,
			int lengthBefore, int lengthAfter) {
		// TODO Auto-generated method stub
		super.onTextChanged(text, start, lengthBefore, lengthAfter);

		Log.i(StaticVariables.DEBUG_TAG, "changedText : "+text); 
	}
	*/
	
	public void setTextWithNoDropdown(String _string){
		setAdapter((SuggestionAdapter)null);
		setText(_string);
		setAdapter(adapter);
	}
	/*
	public void stopAllTasks(){
		for(int i=0;i<taskList.size();i++){
			taskList.get(i).cancel(true);
		}
		taskList.clear();
	}
	  */
	public void reset(){
		setUserHasChosenASuggestion(false);
		this.setText("");  
		currentSuggestion=null;
		dismissDropDown();
		//stopAllTasks();
	}
	
	private SuggestionEditText getThis(){
		return this;
	}
	
	public void initialize(Context context){
		//String[] sArray={"abc","xyz"};
		//updateAdapterWithArray(sArray);
		adapter = new SuggestionAdapter(getContext());
		this.setAdapter(adapter);
		this.setThreshold(2);  
		this.setTextColor(Color.BLACK);  
		this.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				setCurrentSuggestion((SuggestionModel)arg0.getAdapter().getItem(arg2));
				setText(getCurrentSuggestion().getAddress());
				setUserHasChosenASuggestion(true);
				/*
				setAdapter((SuggestionAdapter)null); // turn off the adapter
				requestFocus();
				Handler handler = new Handler() {
				public void handleMessage(Message msg) {
				    ((SuggestionEditText)msg.obj).setAdapter(adapter);
				    };
				};
				Message msg = handler.obtainMessage();
				msg.obj = getThis();
				handler.sendMessageDelayed(msg, 100); 
				Log.i(StaticVariables.DEBUG_TAG, "goes here");
				// TODO Auto-generated method stub
				*/
			}
		});
	}

	public SuggestionEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		initialize(context);
	}

	public SuggestionEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		initialize(context);
	}

	public SuggestionEditText(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		initialize(context);
	}
	
	public void setCurrentSuggestion(SuggestionModel currentSuggestion) {
		this.currentSuggestion = currentSuggestion;
	}

	public SuggestionModel getCurrentSuggestion() {
		return currentSuggestion;
	}

	public void setUserHasChosenASuggestion(boolean userHasChosenASuggestion) {
		this.userHasChosenASuggestion = userHasChosenASuggestion;
	}

	public boolean isUserHasChosenASuggestion() {
		return userHasChosenASuggestion;
	}
	
	public void fillWithModel(SuggestionModel suggestion){
		setCurrentSuggestion(suggestion);
		if(suggestion!=null){
			setUserHasChosenASuggestion(true);
			setText(suggestion.getAddress());
		}else{
			setUserHasChosenASuggestion(false);
			setText("");
		}
	}
/*
	public class SuggestionTextWatcher implements TextWatcher{
		
		private boolean shouldAutoComplete=true;
		private String currentText="";
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			if(shouldAutoComplete){
				
				FetchSuggestionTask myTask=new FetchSuggestionTask();
				//pause all previous TASK
				for(int i=0;i<taskList.size();i++){
					taskList.get(i).cancel(true);
				}
				taskList.add(myTask);
				myTask.execute(currentText);
				
			}
			
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			
			currentText=s.toString();
			shouldAutoComplete=true;
			for(int i=0;i<adapter.getCount();i++){
				SuggestionModel iSuggestion=adapter.getItem(i);
				if(iSuggestion.getAddress().equalsIgnoreCase(currentText)){
					shouldAutoComplete=false;
					break;
				}
			}
			
			
		}
		
	}
	*/
	/*
	public class FetchSuggestionTask extends AsyncTask<String, Void, ArrayList<SuggestionModel>>{

		@Override
		protected ArrayList<SuggestionModel> doInBackground(String... params) {
			// TODO Auto-generated method stub
			ArrayList<SuggestionModel> resultList=new ArrayList<SuggestionModel>();
			String inputText=params[0];
			//replace all SPACE character with plus sign
			HttpClient httpClient=new DefaultHttpClient();
			InputStream inputStream=null;
			String fetchedString=null;
			StringBuilder stringBuilder=null;
			
			String fetchQuery=StaticVariables.GOOGLE_PLACES_API+inputText;
			String correctFormatQuery=MyUtilities.convertURL(fetchQuery);
			try {
				//Request and get the Response
				HttpResponse response=httpClient.execute(new HttpGet(correctFormatQuery));
				//the put to an inputStream
				inputStream=response.getEntity().getContent();
				//create a reader to read that inputStream
				BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				//a stringbuilder to combine each line of the inputStream
				stringBuilder=new StringBuilder();
				//begin to read
				String line=null;
				while((line=reader.readLine())!=null){
					stringBuilder.append(line+"\n");
				}
				//after finish reading, we close the inputStream
				inputStream.close();
				//got the fetchedString from the builder
				fetchedString=stringBuilder.toString();
				//parse JSON and store to our Model
				SuggestionJSONParser jsonParser=new SuggestionJSONParser();
				resultList=jsonParser.parse(fetchedString);
				
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//call web service API
			return resultList;
		}
		@Override
		protected void onPostExecute(ArrayList<SuggestionModel> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//logResult(result);
			taskList.clear();  
			
			
			adapter.updateData(result);
			//if(!isPopupShowing()&&!isUserHasChosenASuggestion()){
				//showDropDown();
			//}
			
		}
		
		private void logResult(ArrayList<SuggestionModel> result){
			for(int i=0;i<result.size();i++){
				SuggestionModel iSuggestion=result.get(i);
				Log.i(StaticVariables.DEBUG_TAG, "Suggestion["+String.valueOf(i)+"] = "+iSuggestion.getAddress());
			}
			Log.i(StaticVariables.DEBUG_TAG, "------------------------------");
		}
	}
	*/

}
